package com.example.xinhuazidian

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.xinhuazidian.adapter.NalanxingdeshijiAdapter
import com.example.xinhuazidian.bean.Nalanxingdeshiji
import com.example.xinhuazidian.databinding.ActivityNalanxingdeshijiBinding
import com.example.xinhuazidian.utils.JsonFileUtil
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gyf.immersionbar.ImmersionBar
import java.lang.reflect.Type

/**
 * 纳兰性德诗集列表
 */
class NalanxingdeshijiActivity : AppCompatActivity(),
    NalanxingdeshijiAdapter.OnRecyclerItemClickListener {

    private lateinit var binding: ActivityNalanxingdeshijiBinding
    private var nalanxingdeshijiAdapter: NalanxingdeshijiAdapter? = null
    private lateinit var mapBeanList: MutableList<Nalanxingdeshiji>
    private var str: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityNalanxingdeshijiBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initView()
        initData()
    }

    private fun initView() {
        //沉浸状态栏
        ImmersionBar.with(this)
            .statusBarDarkFont(true)//状态栏字体是深色，不写默认为亮色
            .init()

        load()
    }

    private fun initData() {
        nalanxingdeshijiAdapter?.setRecyclerItemClickListener(this)
    }

    @SuppressLint("SetTextI18n")
    private fun load() {
        str = JsonFileUtil.loadFile(this, "nalanshiji.json")

        val mapBeanListType: Type = object : TypeToken<ArrayList<Nalanxingdeshiji?>?>() {}.type
        mapBeanList = Gson().fromJson(str, mapBeanListType)
        initAdapter(mapBeanList)

        binding.tvNum.text = "一共${mapBeanList.size}首"
    }

    private fun initAdapter(list: MutableList<Nalanxingdeshiji>) {
        val staggeredGridLayoutManager =
            StaggeredGridLayoutManager(1, LinearLayoutManager.VERTICAL)
        binding.rv.layoutManager = staggeredGridLayoutManager

        //加载适配器
        nalanxingdeshijiAdapter = NalanxingdeshijiAdapter(list)
        binding.rv.adapter = nalanxingdeshijiAdapter
    }

    override fun onRecyclerItemClick(position: Int) {
        intent = Intent(this, NalanshijiXiangqingActivity::class.java)
        intent.putExtra("bean", Gson().toJson(mapBeanList[position]))
        startActivity(intent)
    }
}